package com.lyx.controller;

import com.lyx.entity.User;
import com.lyx.service.UserService;
import com.lyx.until.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;

/**
 * --- Be Humble and Hungry ---
 *
 * @author McMeloxD
 * @date 2024/8/1
 * @desc 用户控制类
 */
@RequestMapping("/sys/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;


    /**
     * 登录
     * @param user,session
     * @return map
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) {
        User user1 = userService.login(user);
        if (user1 != null) {
            // 1 登录成功,生成令牌
            String token = UUID.randomUUID( ).toString( ).replace("-", "");
            //登陆成功存用户信息
            session.setAttribute("userInfo", user1);
            //将令牌返回前端
            HashMap<String,String> map = new HashMap<>();
            map.put("token", token);
            return R.ok(map);
        }
        return R.ok(50000,"密码错误");
    }

    /**
     * 获取用户信息
     * @param session
     * @return info
     */
    @GetMapping("/getInfo")
    public R getUserInfo(HttpSession session){
        User Info = (User)session.getAttribute("userInfo");
        return R.ok(Info);
    }

    /**
     * 退出
     * @param session
     * @return R
     */
    @PostMapping("/logout")
    public R logout(HttpSession session, HttpServletRequest request){
        //清除session
        session.removeAttribute("userInfo");
        return R.ok();
    }
}
